import axios from 'axios'
import router from '@/router'
import { MessageBox, Message } from 'element-ui'
import md5 from 'js-md5'
import { login } from '@/api/system'
let istime = Date.parse(new Date()) - 5000
// swag地址 http://124.70.196.178:8080/intelligent_control_webservice_eeds/doc.html
// 设置请求的地址
// axios.defaults.baseURL = '/'
// axios.defaults.baseURL = 'https://60462w5f31.zicp.fun' // 打包地址（线上）

// 请求超时时间
axios.defaults.timeout = 10000
// 允许跨域
axios.defaults.withCredentials = false
// 设置默认的Content-Type
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

function decode(str) {
  return decodeURIComponent(
    atob(str)
      .split('')
      .map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
      })
      .join('')
  )
}
// axios请求拦截器，可以统一给所有axios请求加上相同的参数，也可以统一新增token
axios.interceptors.request.use(
  config => {
    let token = window.localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = token
    }
    if (config.data && config.method == 'post') {
      axios.defaults.headers.post['Content-Type'] = 'application/json'
    }
    return config
  },
  error => {
    return Promise.error(error)
  }
)

const get = (url, params) => {
  return new Promise((resolve, reject) => {
    axios
      .get(`${url}`, { params: params })
      .then(res => {
        if (res.data.code === 200) {
          //成功
          resolve(res.data)
        } else if (res.data.code === 421) {
          //未登录
          let nowtime = Date.parse(new Date())
          if (nowtime - istime > 5000) {
            if (router.currentRoute.query && router.currentRoute.query.user) {
              let username = decode(router.currentRoute.query.user)
              let password = decode(router.currentRoute.query.psd)
              password = md5(md5(password) + 'bby')
              login({
                password: password,
                username: username
              }).then(res => {
                window.localStorage.setItem('token', res.data.token)
                window.localStorage.setItem('roleId', res.data.roleId)
                location.reload()
              })
            } else {
              MessageBox.confirm(`${res.data.msg}，可以取消继续留在该页面，或者重新登录`, '重新登录', {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                router.push({ path: `/?redirect=${router.currentRoute.path}` })
              })
            }
            istime = Date.parse(new Date())
          }
        } else {
          Message.error(res.data.msg)
        }
      })
      .catch(error => {
        reject(error.data)
      })
  })
}

const post = (url, params) => {
  return new Promise((resolve, reject) => {
    axios
      .post(`${url}`, params)
      .then(res => {
        if (res.data.code === 200) {
          //成功
          resolve(res.data)
        } else if (res.data.code === 421) {
          //未登录
          MessageBox.confirm(`${res.data.msg}，可以取消继续留在该页面，或者重新登录`, '重新登录', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            router.push({ path: `/?redirect=${router.currentRoute.path}` })
          })
        } else {
          Message.error(res.data.msg)
        }
      })
      .catch(error => {
        reject(error.data)
      })
  })
}

const del = (url, params) => {
  return new Promise((resolve, reject) => {
    axios
      .delete(`${url}`, { params: params })
      .then(res => {
        if (res.data.code === 200) {
          //成功
          resolve(res.data)
        } else if (res.data.code === 421) {
          //未登录
          MessageBox.confirm(`${res.data.msg}，可以取消继续留在该页面，或者重新登录`, '重新登录', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            router.push({ path: `/?redirect=${router.currentRoute.path}` })
          })
        } else {
          Message.error(res.data.msg)
        }
      })
      .catch(error => {
        reject(error.data)
      })
  })
}

export { get, post, del }
